import { defineComponent } from 'vue';
import { BasicForm, useForm } from '@/components/Form';
import { BasicModal, useModalInner } from '@/components/Modal';
import { useMessage } from '@/hooks/web/useMessage';
import { addViolationApi, updateViolationApi } from '../service';
import { getStudentListApi } from '../../studentInfo/service';
import { Category } from '..';

export default defineComponent({
  name: 'ActionModal',
  emits: ['register', 'reload'],
  setup(_, { emit }) {
    const {
      createMessage: { success },
    } = useMessage();

    const [registerModal, { changeLoading, changeOkLoading, closeModal, setModalProps }] =
      useModalInner(async ({ record, type = 'add' }) => {
        changeLoading(true);
        changeOkLoading(true);
        setModalProps({ title: `${type === 'add' ? '新增' : '编辑'}违规` });
        if (type === 'edit') {
          await setFieldsValue(record || {});
        }
        changeLoading(false);
        changeOkLoading(false);
      });

    const [registerForm, { validate, setFieldsValue }] = useForm({
      labelWidth: 90,
      baseColProps: { span: 24 },
      schemas: [
        {
          field: 'ViolationID',
          label: 'ViolationID',
          show: false,
          component: 'Input',
        },
        {
          field: 'Category',
          label: '违规类型',
          component: 'Select',
          componentProps: {
            options: Category,
          },
          required: true,
        },
        {
          field: 'UserID',
          label: '违规人',
          component: 'ApiSelect',
          required: true,
          componentProps: ({ formModel }) => ({
            api: async () => {
              const res = await getStudentListApi({ page: 1, pageSize: 100 });
              formModel.userOptions = res.data.records;
              return res.data;
            },
            resultField: 'records',
            labelField: 'UserName',
            valueField: 'UserID',
            onChange: (UserID) => {
              const target = (formModel.userOptions || []).find((item) => item.UserID === UserID);
              formModel.UserName = target?.UserName || '';
            },
          }),
        },
        {
          field: 'UserName',
          label: '学生名称',
          component: 'Input',
          required: true,
          show: false,
        },
        {
          field: 'ViolationTime',
          label: '违规时间',
          component: 'DatePicker',
          componentProps: {
            style: {
              width: '100%',
            },
            showTime: true,
            format: 'YYYY-MM-DD HH:mm:ss',
          },
          required: true,
        },
        {
          field: 'Description',
          label: '描述',
          component: 'InputTextArea',
          required: true,
          rules: [{ max: 200, message: '名称不能超过200个字符' }],
          componentProps: { placeholder: '请输入', rows: 10, showCount: true, maxlength: 200 },
        },
      ],
      showActionButtonGroup: false,
    });

    const handleSubmit = async () => {
      changeLoading(true);
      changeOkLoading(true);

      try {
        const values = await validate();
        if (!values.ViolationID) {
          await addViolationApi(values);
          success('新增成功');
        } else {
          await updateViolationApi(values);
          success('更新成功');
        }
        closeModal();
        emit('reload');
      } finally {
        changeLoading(false);
        changeOkLoading(false);
      }
    };

    return () => (
      <BasicModal
        width={600}
        minHeight={300}
        onRegister={registerModal}
        destroyOnClose
        onOk={handleSubmit}
      >
        <div class="px-4">
          <BasicForm onRegister={registerForm} />
        </div>
      </BasicModal>
    );
  },
});
